﻿using System;
using System.Collections.Generic;
using System.ServiceModel.DomainServices.Client;
using System.Linq;
using ObservableCollections.Interfaces;

namespace ObservableCollections.Extensions
{
    public static class DomainContextExtensions
    {
        public static void UndoEntities<T>(this DomainContext context, Action action) where T:Entity
        {
            var items = context.EntityContainer.GetChanges().ModifiedEntities.Where(e => e is T).ToList();
            items.ForEach(entity => entity.Undo());
            if(action!=null) action.Invoke();
        }

        public static List<T> GetModifiedEntities<T>(this DomainContext context) where T:Entity
        {
            List<T> items;
            if (typeof(ICollectionChanged).IsAssignableFrom(typeof(T)))
                items = context.EntityContainer.GetEntitySet<T>().Where(arg => (arg as ICollectionChanged).IsEntityChanged == true).ToList();
            else
                items = context.EntityContainer.GetChanges().ModifiedEntities.OfType<T>().ToList();
            return items;
        }
    }
}
